import htmx from "htmx.org";
window.htmx = htmx;

import { ready, assert } from "@/lib/utils";
import { addFormSubmitEvent } from "@/lib/form";
import { setupEditorForFormFields } from "@/components/wang-editor-next"
import { setupFileUploadFormFields } from "@/components/file-uploader";
import { setupSelectDefaultElems } from "@/components/select";

const sidebarElem = document.getElementById("sidebar");
const sidebarCloseButton = document.getElementById("sidebar-close-btn");
const sidebarShowBtnElem = document.getElementById("sidebar-show-btn");

function restoreSidebarVisibility() {
    assert(sidebarElem, "Element with ID `sidebar` cannot be found!");
    assert(sidebarShowBtnElem, "Element with ID `sidebar-show-btn` cannot be found!")
    
    const isHidden = localStorage.getItem('sidebarHidden') === 'true';
    if (isHidden) {
        sidebarElem.classList.add('tw:hidden');
        sidebarShowBtnElem.classList.remove("tw:hidden");
    } else {
        sidebarElem.classList.remove('tw:hidden');
        sidebarShowBtnElem.classList.add("tw:hidden");
    }
}

function toggleSideBar() {
    assert(sidebarElem, "Element with ID `sidebar` cannot be found!");

    assert(sidebarShowBtnElem, "Element with ID `sidebar-show-btn` cannot be found!")

    const isHidden = sidebarElem.classList.toggle('tw:hidden');
    sidebarShowBtnElem.classList.toggle("tw:hidden");

    localStorage.setItem('sidebarHidden', isHidden.toString());
}

function setupSideBar() {
    // When `hide_sidebar` is true, there is no sidebarElem 
    if (!sidebarElem) return;  
    restoreSidebarVisibility();
        
    assert(sidebarCloseButton, "Element with ID `sidebarCloseButton` doesn't exist!");
    assert(sidebarShowBtnElem, "Element with ID `sidebar-show-btn` cannot be found!")
        
    sidebarCloseButton.addEventListener('click', toggleSideBar);
    sidebarShowBtnElem.addEventListener('click', toggleSideBar);
}

function setupAuditForm() {
    const AuditFormElem = document.getElementById('by6-audit-form') as HTMLFormElement;
    if (!AuditFormElem) return;
    addFormSubmitEvent(AuditFormElem, () => {
        const modal = document.getElementById("by6_modal_xl") as HTMLDialogElement;
        modal.close();
        // TODO when current page has form that has unsaved(posted) data, then notify user
        window.location.reload();
    })
}


function htmxAfterSettleHandler(_event: CustomEvent<any>) {
    setupEditorForFormFields();
    setupFileUploadFormFields();
    setupSelectDefaultElems();
}

(function () {
    ready(() => {
        setupSideBar();
        setupAuditForm();
        setupSelectDefaultElems();

        // some HTMX components page uses form containing WangEditorNext field
        document.body.addEventListener<any>('htmx:afterSettle', htmxAfterSettleHandler);
    });
})();
